// pages/oneself/balance/withdraw/withdraw.js
const app = getApp()
const connector = require('../../../../utils/connector.js')
const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
let ctx;
let setTin;
let tmplId3 = 'r5sKumwIVX5XWCNUp0KP1vQIqciZbbPZ11RJ8-fS2cE'//提现结果通知
let tmplId2 = 'VPmChZMp46UoBgsaffCc8Y-wpU9xjZSicTmpVBwb3M8'//提现审核通知
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    srcs:"",
    money:"",
    text: '',
    numbers:90,
    logs: []
  },
  // 验证码刷新
  change: function() {
    let that = this;
    captcha(that)
    // drawPic(that);
    that.setData({
      numbers:90
    })
},
  // 验证码刷新
  images(e){
    let that = this
    // captcha(that)
  },
  //表单提交
  formSubmit: function (e) {
    let that = this
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let list = e.detail.value
    if (list.name == '') {
      connector.showToasts("请输入姓名")
      return false
    }
    if (list.telephone == '') {
      connector.showToasts("请输入联系电话")
      return false
    } else {
      if (list.telephone.length < 11 || !myreg.test(list.telephone)) {
        connector.showToasts("联系电话输入有误")
        return false
      }
    }
    if(list.amont_money > that.data.money){
      connector.showToasts("提现金额不能大于可提现积分")
      return false
    }
    if (list.amont_money == '') {
      connector.showToasts("请输入提现金额")
      return false
    }else{
      if(list.amont_money % 10 != 0){
        connector.showToasts("提现金额必须为整十")
        return false
      }
    }
    if (list.code == '') {
      connector.showToasts("请输入验证码")
      return false
    }
    wx.requestSubscribeMessage({
      tmplIds: [tmplId2,tmplId3],
      success (res) { 
        if(res.errMsg == "requestSubscribeMessage:ok"){
          connector.showToasts("操作成功")
          userWithdraw(that,list)
        }else{
          connector.showToasts("操作失败，请重试")
          userWithdraw(that,list)
        }
        // console.log(res)
      },
      fail:function(res){
        console.log(res)
      }
    })

    // console.log(list)
    // userWithdraw(that,list)

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log(options)
    that.setData({
      money:options.money
    })
    setTin = setInterval(function(){
      let numbers = that.data.numbers
      if(numbers>0){
        that.setData({
          numbers:that.data.numbers - 1
        })
      }else{
        that.setData({
          numbers:90
        })
        captcha(that);
      }
    },1000)
    // let str = 'ABCEFGHJKLMNPQRSTWXY123456789';
    // let strs = str.split("")
    // console.log(strs)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    captcha(that)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {
    var that = this
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(setTin)
  }
})
//获取验证码
function captcha(that){
  connector.getFunc(connector.connector().captcha, "", "get", app.tokens, function (res) {
    // console.log(res)
    if (res.statusCode == 200) {
      // console.log(res.data.result)
      drawPic(that,res.data.result)
      // that.setData({
      //   money:res.data.result
      // })
    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
  // console.log(connector.connector().captcha)
  // wx.getImageInfo({
  //   src: connector.connector().captcha, 
  //   success: function (res) {
  //     console.log(res)
  //     that.setData({
  //       srcs: res.path
  //     })
  //   }
  // })
  

}
//提现
function userWithdraw(that,obj){
  console.log(obj)
  wx.request({
    url: connector.connector().userWithdraw,
    method: "post",
    header: {
      token:  app.tokens,
    },
    dataType: 'json',
    data: obj,
    success: function(res){
      if(res.statusCode == 200){
        if(res.data.code == 1){
          wx.navigateBack({
            delta: 1,
          })
        }else{
          connector.showToasts(res.data.msg)
        }
      }else{
        connector.showToasts("内部错误")
      }
      
      console.log(res)
    },
    file:function(res){
      console.log(res)
    },
  })
  // wx.request({
  //   url: connector.connector().userWithdraw,
  //   method: "post",
  //   header: {
  //     token:  app.tokens,
  //   },
  //   data: "",
  //   success: (ser) => {
  //     console.log('res', ser);
  //     console.log(ser.header['Set-Cookie'])
  //     let cookieStr = ser.header['Set-Cookie']
  //     let cookies = cookieStr.split('; ')
      
   
  //   }
  // })
      
}


function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}
/**生成一个随机色**/
function randomColor(min, max) {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return "rgb(" + r + "," + g + "," + b + ")";
}

/**绘制验证码图片**/
function drawPic(that,nums) {
  ctx = wx.createCanvasContext('canvas');
  /**绘制背景色**/
  ctx.fillStyle = randomColor(180, 240); //颜色若太深可能导致看不清
  ctx.fillRect(0, 0, 90, 28)
  /**绘制文字**/
  let arr;
  let text = '';
  let str = nums.split("")
    console.log(str)
  // let str = 'ABCEFGHJKLMNPQRSTWXY123456789';
  // str.split(separator, limit)
  // let str =[1,2,3,4];
  for (let i = 0; i < 4; i++) {
      // let txt = str[randomNum(0, str.length)];
      let txt = str[i];

      ctx.fillStyle = randomColor(50, 160); //随机生成字体颜色
      ctx.font = randomNum(20, 26) + 'px SimHei'; //随机生成字体大小
      let x = 5 + i * 20;
      let y = randomNum(20, 25);
      let deg = randomNum(-20, 20);
      //修改坐标原点和旋转角度
      ctx.translate(x, y);
      ctx.rotate(deg * Math.PI / 180);
      ctx.fillText(txt, 5, 0);
      text = text + txt;
      //恢复坐标原点和旋转角度
      ctx.rotate(-deg * Math.PI / 180);
      ctx.translate(-x, -y);
  }
  /**绘制干扰线**/
  for (let i = 0; i < 4; i++) {
      ctx.strokeStyle = randomColor(40, 180);
      ctx.beginPath();
      ctx.moveTo(randomNum(0, 90), randomNum(0, 28));
      ctx.lineTo(randomNum(0, 90), randomNum(0, 28));
      ctx.stroke();
  }
  /**绘制干扰点**/
  for (let i = 0; i < 20; i++) {
      ctx.fillStyle = randomColor(0, 255);
      ctx.beginPath();
      ctx.arc(randomNum(0, 90), randomNum(0, 28), 1, 0, 2 * Math.PI);
      ctx.fill();
  }
  ctx.draw(false, function() {
      that.setData({
          text: text
      })
  });
}